package com.infocollect.common.sms;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.infocollect.common.utils.http.HttpUtils;
import com.infocollect.common.utils.sign.Md5Utils;
import com.infocollect.framework.web.domain.server.Sys;
import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MascloudSmsUtil {

    public static final String EC_NAME = "杭州市教育考试院";
    public static final String AP_ID = "hzksymasH";
    public static final String SECRET_KEY = "Hzzk@123456";
    public static final String SIGN = "jHbH69hp0";
    public static final String ADD_SERIAL = "";

    public static String toMD5(String originalString) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(originalString.getBytes());
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Could not find MD5 algorithm", e);
        }
    }
    public static String getSmsParam(String mobile, String msg)
    {
        StringBuffer bf = new StringBuffer();
        bf.append(EC_NAME).append(AP_ID).append(SECRET_KEY).append(mobile).append(msg)
                .append(SIGN).append(ADD_SERIAL);
        String selfMac = toMD5(bf.toString());

        JSONObject json = new JSONObject();
        json.put("ecName",EC_NAME);
        json.put("apId",AP_ID);
        json.put("mobiles",mobile);
        json.put("content",msg);
        json.put("sign",SIGN);
        json.put("addSerial",ADD_SERIAL);
        json.put("mac",selfMac);

        String para = json.toString();
        System.out.println(para);

        return Base64.encodeBase64String(para.getBytes());



    }

    public static void sendSms(String mobile, String msg) throws Exception
    {
        String param = getSmsParam(mobile,msg);
        String result = HttpUtils.sendPost("http://112.35.1.155:1992/sms/norsubmit", param);
        JSONObject json = JSON.parseObject(result);
        if(!(json!=null&&"success".equals(json.get("rspcod"))&&((Boolean) json.get("success")).booleanValue()==true))
        {
            throw new Exception("数据校验错误");
        }

    }
}
